package com.dify.service.impl;




import java.util.Arrays;
import java.util.HashMap;


import com.alibaba.fastjson2.JSON;
import com.dify.domain.req.DifyRequestBody;
import com.dify.domain.resp.BlockResponse;
import com.dify.domain.resp.StopResponse;
import com.dify.domain.resp.StreamResponse;
import com.dify.service.DifyService;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;





@Component
public class DifyServiceImpl implements DifyService {

    @Value("${dify.url}")
    private String url;

    @Value("${dify.stopUrl}")
    private String stopUrl;

    @Resource
    private  RestTemplate restTemplate;

    @Resource
    private  WebClient webClient;

    /**
     * 流式调用dify.
     *
     * @param query  查询文本
     * @param userId 用户id
     * @param apiKey apiKey 通过 apiKey 获取权限并区分不同的 dify 应用
     * @return Flux 响应流
     */
    @Override
    public Flux<StreamResponse> streamingMessage(String conversationId, String upContext, String query, String userId, String apiKey) {

        //是否携带上下文,封装上下文  废弃 搞笑用的
        if(StringUtils.isNotEmpty(upContext)){
            query = "这是我的历史提问：\n" + upContext + "\n现在我的问题是：\n"+ query ;
        }

        //1.设置请求体
        DifyRequestBody body = new DifyRequestBody();
        body.setInputs(new HashMap<>());
        body.setQuery(query);
        body.setResponse_mode("streaming");
        body.setConversation_id(conversationId);
        body.setUser(userId);

        //2.使用webclient发送post请求
        return webClient.post()
                .uri(url)
                .headers(httpHeaders -> {
                    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                    httpHeaders.setBearerAuth(apiKey);
                })
                .bodyValue(JSON.toJSONString(body))
                .retrieve()
                .bodyToFlux(StreamResponse.class);
    }







    @Override
    public StopResponse stopMessage(String taskId, String userId, String apiKey) {

        //1.设置请求体
        DifyRequestBody body = new DifyRequestBody();
        body.setInputs(new HashMap<>());
        body.setUser(userId);
        //2.设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setBearerAuth(apiKey);
        //3.封装请求体和请求头
        String jsonString = JSON.toJSONString(body);
        HttpEntity<String> entity = new HttpEntity<>(jsonString, headers);
        String targetUrl = String.format(stopUrl, taskId);

        //4.发送post请求
        ResponseEntity<StopResponse> stringResponseEntity =
                restTemplate.postForEntity(targetUrl, entity, StopResponse.class);
        //5.返回响应体
        return stringResponseEntity.getBody();
    }
}